package dome_013;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;

/**
 * <p>Description: [阅读concurrentskiplistmap]</p>
 * Created on 2020/12/14
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class T01_ConcurrentMap {

    public static void main(String[] args) {
        Map<String, String> map1 = new ConcurrentHashMap<String, String>();
        Map<String, String> map2 = new ConcurrentSkipListMap<String, String>(); //高并发并且排序
        Map<String, String> map3 = new Hashtable<String, String>();
        Map<String, String> map4 = new HashMap<String, String>();

        test(map1, "ConcurrentHashMap");
        test(map2, "ConcurrentSkipListMap");
        test(map3, "Hashtable");
        test(map4, "HashMap");
    }

    private static void test(Map<String, String> map, String name) {
        Random random = new Random();
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);
        long start = System.currentTimeMillis();
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    map.put("a" + random.nextInt(100000), "a" + random.nextInt(100000));
                }
                latch.countDown();
            });
        }

        Arrays.asList(threads).forEach(t -> t.start());
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println(String.format("[%s]-消耗时间:[%s] ms", name, (end - start)));
    }
}
